package com.supersit.GZFDA.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2015/11/3.
 */
public class CatchContextException implements Thread.UncaughtExceptionHandler {
    public static final String TAG = "CatchContextException";
    //程序context
    private Context mContext;
    //系统默认Exception处理器
    private Thread.UncaughtExceptionHandler mDefaultHandler;


    //存储设备信息和异常信息
    private Map<String, String> info = new HashMap<String, String>();

    //格式化日期
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    private static CatchContextException ourInstance = new CatchContextException();

    public static CatchContextException getInstance() {
        return ourInstance;
    }

    private CatchContextException() {
    }

    public void init(Context context) {
        this.mContext = context;
        //获取系统默认的Exception处理器
        this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //设置该类为默认Exception处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!catchException(ex) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //退出程序
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);
            }
        }
    }

    /**
     * 自定义错误处理
     *
     * @param ex
     * @return
     */
    public boolean catchException(Throwable ex) {
        if (ex == null) return false;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext, "很抱歉，程序出现异常，即将退出", Toast.LENGTH_LONG).show();
              //  T.showLong(mContext, "很抱歉，程序出现异常，即将退出");
                Looper.loop();
            }
        }).start();
        collectDeviceInfo();
        saveCrashInfo2File(ex);
        return true;
    }

    /**
     * 收集设备信息
     */
    public void collectDeviceInfo() {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageManager.
                            getInstallerPackageName("com.supersit.greensproject"),
                    PackageManager.GET_ACTIVITIES);
            if (packageInfo != null) {
                String VersionName = packageInfo.versionName
                        == null ? "null" : packageInfo.versionName;
                String VersionCode = packageInfo.versionCode + "";
                info.put("VersionName", VersionName);
                info.put("VersionCode", VersionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                info.put(field.getName(), field.get(null).toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String saveCrashInfo2File(Throwable ex) {
        StringBuffer stringBuffer = new StringBuffer();
        for (Map.Entry<String, String> entry : info.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            stringBuffer.append(key + "=" + value + "\n");
        }
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable throwable = ex.getCause();
        while (throwable != null) {
            throwable.printStackTrace(printWriter);
            throwable = throwable.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        stringBuffer.append(result);
        FileOutputStream fos = null;
        try {
            long timestamp = System.currentTimeMillis();
            String time = formatter.format(new Date());
            String fileName = "crash-" + time + "-" + timestamp + ".log";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = "/sdcard/GZFDA/";
                File dir = new File(path);
                if (dir.exists()) {
                    dir.mkdirs();
                }
                fos = new FileOutputStream(path + fileName);
                fos.write(stringBuffer.toString().getBytes());
                fos.close();
            }
            return fileName;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
